// 游戏行为动作

/**
 * 搜鱼函数
 * 该函数根据预设的坐标执行搜鱼操作
 * @param {object} phoneModelConfig - 手机型号配置
 */
function fishing(phoneModelConfig) { 
    console.log("开始搜鱼");

    // 点击空白区域，防止弹窗
    click(phoneModelConfig.fishing_start_1.x, phoneModelConfig.fishing_start_1.y);
    sleep(1000);
    click(phoneModelConfig.fishing_start_2.x, phoneModelConfig.fishing_start_2.y);

    // 点击进攻按钮
    click(phoneModelConfig.fishing_start_3.x, phoneModelConfig.fishing_start_3.y);
    sleep(1000);
    // 搜索对手
    click(phoneModelConfig.fishing_start_4.x, phoneModelConfig.fishing_start_4.y);
}

/**
 * 获取资源数函数
 * 该函数通过API获取用户的资源数量（金币、圣水、黑油）
 * @param {string} recognizeUrl - 资源识别接口URL
 * @param {string} userKey - 用户标识符
 * @returns {object|null} 包含金币、圣水、黑油数量的对象，失败时返回null
 */
function getResources(recognizeUrl, userKey) {
    //post 请求
    const response = http.post(recognizeUrl, {
        user_key: userKey
    });
    if (response.statusCode === 200) {
        const responseData = response.body.json();
        // 返回资源对象而不是打印
        return {
            gold: responseData.message[0],
            elixir: responseData.message[1],
            darkElixir: responseData.message[2]
        };
    } else {
        try {
            const errorData = response.body.json();
            log(`获取资源数失败，状态码: ${response.statusCode}，错误信息: ${errorData.detail}`);
        } catch (parseError) {
            log(`获取资源数失败，状态码: ${response.statusCode}，原始错误信息: ${response.statusMessage}`);
        }
        return null;
    }
}


//下兵函数
function sendArmy(phoneModelConfig,bingConfig) { 
    console.log("开始下兵");
    // console.log(phoneModelConfig);
    gestures([500, [300, 800], [1000, 500]],
         [500, [1500, 300], [1000, 500]]);

    var numberMap = {
        1: "one",
        2: "two",
        3: "three",
        4: "four",
        5: "five",
        6: "six",
        7: "seven",
        8: "eight",
        9: "nine",
        10: "ten",
        11: "eleven"
    };

    // 配兵占了几个格子
    var troopSlotsOccupied = parseInt(phoneConfig.peibing.troopSlotsOccupied);

    // 第几个格子需要滑动
    var troopSlotToSwipe = parseInt(phoneConfig.peibing.troopSlotToSwipe);

    // 第几个格子英雄有技能
    var troopSlotWithHeroSkill = phoneConfig.peibing.troopSlotWithHeroSkill;


    sleep(1000);
    swipe(
        1371,
        816,
        1382,
        1219,
        1200
    );
    for (var i = 0; i < troopSlotsOccupied; i++) {
        var number = i + 1;
        var numberName = numberMap[number]; 
      

        if (number == troopSlotToSwipe) { 
            console.log("需要滑动");
            click(phoneModelConfig[numberName].x, phoneModelConfig[numberName].y);
            sleep(1000);
            press(phoneModelConfig.swipe_start.x, phoneModelConfig.swipe_start.y, 500);
            swipe(phoneModelConfig.swipe_start.x, phoneModelConfig.swipe_start.y, phoneModelConfig.swipe_end.x, phoneModelConfig.swipe_end.y, 3000);
            
        // } else if (troopSlotWithHeroSkill.includes(number)) {
        //     console.log("英雄有技能");
        //     click(phoneModelConfig[numberName].x, phoneModelConfig[numberName].y);
        //     sleep(1000);
        //     press(phoneModelConfig.swipe_start.x, phoneModelConfig.swipe_start.y, 500);
        //     swipe(phoneModelConfig.swipe_start.x, phoneModelConfig.swipe_start.y, phoneModelConfig.swipe_end.x, phoneModelConfig.swipe_end.y, 3000);


        }

        
        else {
            click(phoneModelConfig[numberName].x, phoneModelConfig[numberName].y);
            sleep(1000);
        
            
            // 添加检查，确保bingConfig[numberName]存在且为有效数值
            if (bingConfig[numberName] && !isNaN(bingConfig[numberName])) {
                var troopCount = parseInt(bingConfig[numberName]);
                
                
                // 如果troopCount大于0，则执行循环
                if (troopCount > 0) {
                    // 修改循环从0开始，这样即使只需要点击一次也能执行
                    for (var j = 0; j < troopCount; j++) {
                        if (j > 0) { // 第一次已经在if外面点击过了
                            // sleep(500);
                            click(phoneModelConfig[numberName].x, phoneModelConfig[numberName].y);
                            
                        }
                        // sleep(500);
                        click(phoneModelConfig.swipe_start.x, phoneModelConfig.swipe_start.y);
                      
                    }
                } else {
                    console.log("下兵次数为0或无效，跳过下兵操作");
                }
            } else {
                console.log("未找到有效的下兵配置：" + numberName);
            }
        }

    }
}

// 夜世界下兵函数
function sendArmyNight(phoneModelConfig, bingConfig) {
    console.log("开始下兵");
    gestures([500, [300, 800], [1000, 500]],
         [500, [1500, 300], [1000, 500]]);

        var numberMap = {
        1: "yone",
        2: "ytwo",
        3: "ythree",
        4: "yfour",
        5: "yfive",
        6: "ysix",
        7: "yseven",
        8: "yeight",
        9: "ynine",
        10: "yten",
        11: "yeleven"
    };
        // 配兵占了几个格子
    var troopSlotsOccupied = parseInt(phoneConfig.ypeibing.troopSlotsOccupied);

    sleep(1000);
    swipe(
        1371,
        816,
        1382,
        1219,
        1200
    );
    for (var i = 0; i < troopSlotsOccupied; i++) {
        var number = i + 1;
        var numberName = numberMap[number];   
        click(phoneModelConfig[numberName].x, phoneModelConfig[numberName].y);
        sleep(1000);
        console.log("点击了" + phoneModelConfig[numberName].x);
    
        

            var troopCount = parseInt(bingConfig[numberName]);
            console.log("下兵次数：" + troopCount);
            
            
            // 如果troopCount大于0，则执行循环
            if (troopCount > 0) {
                // 修改循环从0开始，这样即使只需要点击一次也能执行
                for (var j = 0; j < troopCount; j++) {
                    if (j > 0) { // 第一次已经在if外面点击过了
                        // sleep(500);
                        click(phoneModelConfig[numberName].x, phoneModelConfig[numberName].y);
                        
                    }
                    // sleep(500);
                    click(phoneModelConfig.swipe_start.x, phoneModelConfig.swipe_start.y);
                    
                }
            } else {
                console.log("下兵次数为0或无效，跳过下兵操作");
            }
        }
    }



// 检测游戏结束
function checkGameEnd(ocrUrl,userName) {
    try {
        console.log("检测游戏是否结束");

        // 发送post
        const re = http.post(ocrUrl, {
            user_key: userName
        }, {
            headers: {
                "Content-Type": "application/json"
            }
        });
        
        // 添加调试信息
        console.log("OCR响应状态码:", re.statusCode);
        
        // 检查响应状态码
        if (re.statusCode !== 200) {
            console.log("OCR请求失败，状态码:", re.statusCode);
            return false;
        }
        
        // 获取响应内容
        const responseText = re.body.string();
        console.log("OCR响应内容:", responseText);
        
        // 解析JSON
        const result = JSON.parse(responseText);
        console.log("OCR解析结果:", JSON.stringify(result));
        
        // 检查result字段是否存在
        if (result.hasOwnProperty('result')) {
            console.log("游戏结束检测结果:", result.result);
            console.log("游戏结束检测结果类型:", typeof result.result);
            // 确保返回布尔值
            const boolResult = Boolean(result.result);
            console.log("转换为布尔值后:", boolResult);
            console.log("checkGameEnd函数即将返回:", boolResult);
            return boolResult;
        } else {
            console.log("OCR响应中没有result字段，默认返回false");
            return false;
        }
    } catch (e) {
        console.error("checkGameEnd函数执行出错:", e);
        return false;
    }
}

// 导出函数
module.exports = {
    fishing: fishing,
    getResources: getResources,
    sendArmy: sendArmy,
    checkGameEnd: checkGameEnd,
    sendArmyNight: sendArmyNight
};